#include <iostream>
#include <vector>

using namespace std;
// 14.最长公共前缀
// 编写一个函数来查找字符串数组中的最长公共前缀。
//如果不存在公共前缀，返回空字符串 ""。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        size_t strsSize = strs.size();
        if(strsSize == 0) return "";
        if(strsSize == 1) return strs[0];
        int last = strs[0].size();  // 最长公共前缀的末尾索引

        for(int i = 1; i < strsSize; i++)
            for(int j = 0; j < strs[0].size(); j++)
                if(strs[i][j] != strs[0][j])    // 如果不相同，就在该位置结束字符串
                {
                    last = min(last, j);
                    break;
                }
        return strs[0].substr(0, last);
    }
};
int main() {
    vector<string> strs1{"flower","flow","flight"};
    cout<<Solution().longestCommonPrefix(strs1)<<endl;  // "fl"

    vector<string> strs2{"dog","racecar","car"};
    cout<<Solution().longestCommonPrefix(strs2)<<endl;  // ""

    vector<string> strs3{"aaa","aa","aaa"};
    cout<<Solution().longestCommonPrefix(strs3)<<endl;  // "aa"
    return 0;
}
